package com.github.ecbp.common.data.builder;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.ecbp.common.api.CommonPage;
import com.github.ecbp.common.resp.BaseVO;
import com.github.ecbp.common.data.utils.TransformUtils;

public class CommonPageBuilder {
    /**
     * 将分页转为分页信息
     *
     * @param pageInfo
     * @return
     */
    public static <T> CommonPage build(IPage<T> pageInfo) {
        CommonPage result = new CommonPage<>();
        result.setTotalPage(pageInfo.getPages());
        result.setCurrent(pageInfo.getCurrent());
        result.setPageSize(pageInfo.getSize());
        result.setTotal(pageInfo.getTotal());
        result.setRecords(pageInfo.getRecords());
        return result;
    }

    /**
     * 将分页转为分页信息, 实体的泛型属性也可以转换
     *
     * @param pageInfo
     * @param target   要转换的类型
     * @return
     */
    public static <T> CommonPage<T> build(IPage pageInfo, Class<T> target) {
        CommonPage result = new CommonPage();
        result.setTotalPage(pageInfo.getPages());
        result.setCurrent(pageInfo.getCurrent());
        result.setPageSize(pageInfo.getSize());
        result.setTotal(pageInfo.getTotal());
        result.setRecords(TransformUtils.listCopy(pageInfo.getRecords(), target));
        return result;
    }

    /**
     * 分页列表数据类型直接强制转换
     * @param pageInfo
     * @param targetClass
     * @param <T>
     * @return
     */
    public static <T> IPage<T> buildPageInfo(IPage pageInfo, Class<T> targetClass) {
        IPage<T> result = (IPage<T>) TransformUtils.copy(pageInfo, Page.class);
        result.setRecords(TransformUtils.listCopy(pageInfo.getRecords(), targetClass));
        return result;
    }
}
